// import 'particletrack.js'

//使用proj4.defs()定义投影
proj4.defs("EPSG:4526", "+proj=tmerc +lat_0=0 +lon_0=114 +k=1 +x_0=38500000 +y_0=0 +ellps=GRS80 +units=m +no_defs");
//使proj4中定义的投影在OpenLayers中可用。
ol.proj.proj4.register(proj4);

//创建"EPSG:4526"的Projection实例，Openlayers将可以从Peoj4js中获取转换函数。
var cgcs2000 = new ol.proj.Projection({
    code: "EPSG:4526",//EPSG code
    // extent: [-180, -90, 180, 90],
    // worldExtent: [-180, -90, 180, 90],
    units: "m"//Projection units: `'degrees'`, `'ft'`, `'m'`, `'pixels'`, `'tile-pixels'` or `'us-ft'.
});
ol.proj.addProjection(cgcs2000);


var wkid = 4326;
var token = "44757c5cb4d96f74d897dc4ba430ffa3";
//创建天地图影像底图
var layerTianDiImg = new ol.layer.Tile({
    source: new ol.source.XYZ({
        url: getLayerUrlByData('image', wkid, token),
        projection: 'EPSG:' + wkid,
        wrapX: true,
        crossOrigin: 'anonymous'
    })
});

/*
 * 获取在线天地图
 * type:获取的瓦片类型，影像、矢量
 * wkid:坐标系
 * token:官网申请的开发者token
 */
function getLayerUrlByData(type, wkid, token) {
    var url = '', layerId, tileMatrixSetId;
    if (type === 'image') {
        url = 'http://t{1-7}.tianditu.com/DataServer?';
        layerId = "img_";
        tileMatrixSetId = wkid === 4326 ? 'c' : "w";
    } else if (type === 'label') {
        url = 'http://t{1-7}.tianditu.com/DataServer?';
        layerId = "cia_";
        tileMatrixSetId = wkid === 4326 ? 'c' : "w";
    } else if (type === 'street') {
        url = 'http://t{1-7}.tianditu.com/DataServer?';
        layerId = "vec_";
        tileMatrixSetId = wkid === 4326 ? 'c' : "w";
    } else if (type === 'street_label') {
        url = 'http://t{1-7}.tianditu.com/DataServer?';
        layerId = "cva_";
        tileMatrixSetId = wkid === 4326 ? 'c' : "w";
    }
    return url + 'T=' + layerId + tileMatrixSetId + '&x={x}&y={y}&l={z}&tk=' + token;
}

let tileLayer = new ol.layer.Tile({
    source: new ol.source.OSM({
        wrapX: false // 是否水平循环
    })
});

const map = new ol.Map({
    // layers: [tileLayer,],
    layers: [layerTianDiImg,],
    target: 'map',
    view: new ol.View({
        center: ol.proj.fromLonLat([113.4491, 22.9156]),
        zoom: 13,
    })
});

const imageStyle = new ol.style.Style({
    image: new ol.style.Circle({
        radius: 2,
        fill: new ol.style.Fill({color: 'red'}),
        stroke: new ol.style.Stroke({color: 'red', width: 1}),
    }),
});

const imageStyle1 = new ol.style.Style({
    image: new ol.style.Circle({
        radius: 2,
        fill: new ol.style.Fill({color: '#FF00FF'}),
        stroke: new ol.style.Stroke({color: '#FF00FF', width: 1}),
    }),
});

const imageStyle2 = new ol.style.Style({
    image: new ol.style.Circle({
        radius: 2,
        fill: new ol.style.Fill({color: '#FFFF00'}),
        stroke: new ol.style.Stroke({color: '#FFFF00', width: 1}),
    }),
});

const imageStyle3 = new ol.style.Style({
    image: new ol.style.Circle({
        radius: 2,
        fill: new ol.style.Fill({color: '#FF4500'}),
        stroke: new ol.style.Stroke({color: '#FF4500', width: 1}),
    }),
});

let source = new ol.source.Vector({
    wrapX: false
});

let vector = new ol.layer.Vector({
    source: source,
    style: imageStyle
});


// 尝试给图层添加标注
var createLabelStyle1 = function (feature) {
    return new ol.style.Style({
        // 文字样式
        text: new ol.style.Text({
            textAlign: 'center',     //对齐方式
            textBaseline: 'middle',    //文本基线
            font: 'normal 16px 微软雅黑',     //字体样式
            text: feature.get('name'),    //文本内容
            // offsetY: -25,    // Y轴偏置
            fill: new ol.style.Fill({        //填充样式
                color: '#000000'
            }),
            // backgroundFill: new ol.style.Fill({      // 填充背景
            //     color: asString([0, 0, 0, 0.6]),
            // }),
            stroke: new ol.style.Stroke({color: '#008B8B', width: 12}),
            // padding: [2, 5, 2, 5],
        })
    });
}

function addVectorLabel() {
    var inputText = '前锋污水厂';
    console.log("inputText:" + inputText);
    //新建一个要素 ol.Feature
    var newFeature = new ol.Feature({
        //几何信息
        geometry: new ol.geom.Point(ol.proj.fromLonLat([113.4531, 22.921])),
        //名称属性
        name: inputText === "" ? '标注点' : inputText,
        // img: '/media/wushui.jpg',
    });
    // ori_pos = ol.proj.fromLonLat([113.4531, 22.921]); // 转至3827
    // cgcs_pos = ol.proj.fromLonLat([113.4531, 22.921], cgcs2000); // CGCS38
    // trans_pos = ol.proj.transform(cgcs_pos,'EPSG:4526','EPSG:3857');
    // console.log(ol.proj.fromLonLat([113.4531, 22.921], cgcs2000))
    // console.log(window.document.location.pathname)
    //设置要素的样式
    newFeature.setStyle(createLabelStyle1(newFeature));
    //将新要素添加到数据源中
    source.addFeature(newFeature);
}
addVectorLabel()

var nowptrack = gfparticletrack;
var index = 0;
var lastIndex = 576;
var iii = 0; // 第iii个文件

function change_simulation_time_display() {
    var obj = document.getElementById("simulation_time");
    console.log(obj.innerText)
    // alert(obj.innerText);
    simulation_time = index * 5 / 60
    obj.innerText= "模拟时长:" + simulation_time.toFixed(3).toString() + " h";
}

// 给map添加一个图层vector
map.addLayer(vector);
const addFeaturePoints = () => {
    // 清除原有点
    // vector.getSource().clear();
    var features = vector.getSource().getFeatures();
    features.forEach((feature) => {
        if (feature["O"].name !== "前锋污水厂" && feature["O"].name !== "2019.12枯季 粒子运动示踪图") {
            vector.getSource().removeFeature(feature);
        }
    });

    var locate_data = function (data) {
        const coordinates1 = [];
        const coordinates2 = [];
        const coordinates3 = [];
        for (var key in data) {
            var item = data[key];
            for (i = 0; i < item.length; i++) {
                var pos = [item[i][0], item[i][1]];
                var pos_3857 = ol.proj.transform(pos, 'EPSG:4526', 'EPSG:3857');
                if (key === "Source1") {
                    coordinates1.push([pos_3857[0], pos_3857[1]]);
                }
                if (key === "Source2") {
                    coordinates2.push([pos_3857[0], pos_3857[1]]);
                }
                if (key === "Source3") {
                    coordinates3.push([pos_3857[0], pos_3857[1]]);
                }

            }
        }

        let geom1 = new ol.geom.MultiPoint(coordinates1);
        let geom2 = new ol.geom.MultiPoint(coordinates2);
        let geom3 = new ol.geom.MultiPoint(coordinates3);

        let feature1 = new ol.Feature(geom1);
        let feature2 = new ol.Feature(geom2);
        let feature3 = new ol.Feature(geom3);
        feature1.setStyle(imageStyle1);
        feature2.setStyle(imageStyle2);
        feature3.setStyle(imageStyle3);
        source.addFeature(feature1); // 把要素添加给vectorSource
        source.addFeature(feature2); // 把要素添加给vectorSource
        source.addFeature(feature3); // 把要素添加给vectorSource

        // 动态修改div标签的内容，显示模拟时间
        change_simulation_time_display()
    }
    var data = nowptrack["Time"+index.toString()]
    locate_data(data)
    index++;
};
// window.setInterval(addFeaturePoints, 1000);
// window.setInterval(addFeaturePoints, 1000);
// addFeaturePoints()

document.getElementById('export-png').addEventListener('click', function () {
    map.once('rendercomplete', function () {
        const mapCanvas = document.createElement('canvas');
        const size = map.getSize();
        mapCanvas.width = size[0];
        mapCanvas.height = size[1];
        const mapContext = mapCanvas.getContext('2d');
        Array.prototype.forEach.call(
            document.querySelectorAll('.ol-layer canvas'),
            function (canvas) {
                if (canvas.width > 0) {
                    const opacity = canvas.parentNode.style.opacity;
                    mapContext.globalAlpha = opacity === '' ? 1 : Number(opacity);
                    const transform = canvas.style.transform;
                    // Get the transform parameters from the style's transform matrix
                    const matrix = transform
                        .match(/^matrix\(([^\(]*)\)$/)[1]
                        .split(',')
                        .map(Number);
                    // Apply the transform to the export map context
                    CanvasRenderingContext2D.prototype.setTransform.apply(
                        mapContext,
                        matrix
                    );
                    mapContext.drawImage(canvas, 0, 0);
                }
            }
        );
        if (navigator.msSaveBlob) {
            // link download attribute does not work on MS browsers
            console.log(iii)
            navigator.msSaveBlob(mapCanvas.msToBlob(), 'map' + iii.toString() + '.png');
        } else {
            const link = document.getElementById('image-download');
            link.href = mapCanvas.toDataURL();
            console.log(iii)
            link.download = 'map' + iii.toString() + '.png';
            link.click();
        }
    });
    map.renderSync();
});

// 暂时使用按钮的形式控制下一帧的播放，之后可以考虑使用setinterval自动播放
// var interval = window.setInterval(function(){
//     if(index >= 140){
//         clearInterval(interval);
//     }
//     addFeaturePoints();
//     //do whatever here..
// }, 100);
document.getElementById('next_frame').addEventListener('click', function () {
    var interval = window.setInterval(function () {
        if (index >= 290) {
            clearInterval(interval);
        }
        addFeaturePoints();
        //do whatever here..
    }, 100);
});



